﻿#include "Matrix.h"


CMatrix::CMatrix() 
{
	setCol(0);
	setRow(0);
}

CMatrix::CMatrix ( unsigned int r, unsigned int c ) :
nRow ( r > 0 && c > 0 ? r : 0 ), 
	nCol ( r > 0 && c > 0 ? c : 0 )
{
	if ( nRow == 0 )
	{
		p = 0;
		return;
	}
	p = new double*[nRow];
	*p = new double[nRow*nCol];
	for ( unsigned int i = 1; i < nRow; ++i ) p[i] = p[i-1] + nCol;
}

CMatrix::CMatrix ( unsigned int r, unsigned int c, const double * const * a ) :
nRow ( r > 0 && c > 0 && a != 0 ? r : 0 ), 
	nCol ( r > 0 && c > 0 && a != 0 ? c : 0 )
{
	if ( nRow == 0 )
	{
		p = 0;
		return;
	}
	p = new double*[nRow];
	*p = new double[nRow*nCol];
	for ( unsigned int i = 0; i < nRow; ++i )
	{
		if ( i ) p[i] = p[i-1] + nCol;
		double * t = p[i];
		const double * s = a[i];
		for ( unsigned int j = 0; j < nCol; ++j ) t[j] = s[j];
	}
}

CMatrix::CMatrix ( const CMatrix & m ) : nRow ( m.nRow ), nCol ( m.nCol )
{
	if ( nRow == 0 )
	{
		p = 0;
		return;
	}
	p = new double*[nRow];
	*p = new double[nRow*nCol];
	for ( unsigned int i = 0; i < nRow; ++i )
	{
		if ( i ) p[i] = p[i-1] + nCol;
		double * t = p[i];
		const double * s = m.p[i];
		for ( unsigned int j = 0; j < nCol; ++j ) t[j] = s[j];
	}
}

CMatrix::~CMatrix()
{
	if ( p )
	{
		delete[] *p;
		delete[] p;
	}
}

void CMatrix::fill ( double d )
{
	if ( p == 0 ) return;
	double * t = *p;
	for ( int i = nRow*nCol; --i >= 0; ) *t++ = d;
}

void CMatrix::resize(uint nRow, uint nCol)
{
	setRow(nRow); setCol(nCol);

	p = new double*[nRow];
	*p = new double[nRow*nCol];
	for ( unsigned int i = 1; i < nRow; ++i ) p[i] = p[i-1] + nCol;
}

CMatrix & CMatrix::operator *= ( double d )
{
	if ( p )
	{
		double * t = *p;
		for ( int i = nRow*nCol; --i >= 0; ) *t++ *= d;
	}
	return *this;
}